/*
 * EEPRomStream.cpp
 *
 *  Created on: 2012. 12. 6.
 *      Author: dalxx
 */

#include <avr/eeprom.h>
#include "EEPRomStream.h"

RingBuffer EEPRomStream::ringBuffer;
EEPRomStream::EEPRomStream() : StringStream() {
}


EEPRomStream::EEPRomStream(char* _buffer, int size) :StringStream(_buffer, size) {
	//this->resetBuffer(_buffer,size);

}

EEPRomStream::~EEPRomStream() {

}



int EEPRomStream::read() {
	if (this->index >= this->size)
		return -1;
	return eeprom_read_byte((unsigned char *) this->buffer+index++);
}

int EEPRomStream::peek() {
	if (this->index >= this->size)
		return -1;
	return eeprom_read_byte((unsigned char *) this->buffer+index);
}



size_t EEPRomStream::write(uint8_t byte) {
	if (this->index >= this->size)
		return this->size;

	while(this->ringBuffer.write(byte)==-1)
	{
		this->writeBuffer();
	}
	this->index++;
	if(eeprom_is_ready ()) this->writeBuffer();

	return 1;
}

int EEPRomStream::writeBuffer() {
	int bfsize=this->ringBuffer.bufferSize();
	int c=this->ringBuffer.read();
	if(c==-1) return -1;
	eeprom_write_byte((unsigned char *) this->buffer+index-bfsize, c);
	return c;
}

void EEPRomStream::flush() {
	while(this->writeBuffer()!=-1);
}

//void EEPRomStream::resetBuffer(int start_index, int size) {
//	this->StringStream::resetBuffer(NULL,size);
//	this->startIndex=start_index;
//}
